package com.wiloon.java8x.zookeeper;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryNTimes;
import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.data.Stat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Created by Roy on 2015/12/23;
 */
public class CuratorClient {
    private static Logger logger = LoggerFactory.getLogger(CuratorClient.class);
    protected static CuratorFramework client = null;

    public static void main(String[] args) throws Exception {
        createPath();
    }

    public static void createPath() throws Exception {
        String url = "192.168.33.64:2181";
        url = "127.0.0.1:52181";

        String path = "/test_path0";
        client = CuratorFrameworkFactory.builder()
                .connectString(url)
                .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000))
                .connectionTimeoutMs(60000).build();
        client.start();

        Stat stat = client.checkExists().forPath(path);
        logger.debug("stat:{}", stat);

        if (stat != null) {
            client.delete().forPath(path);
        }
        stat = client.checkExists().forPath(path);
        if (stat == null) {
            try {
                client.create().forPath(path, "testValue0".getBytes());
            } catch (Exception e) {
                logger.error("failed to create node:{}", e.toString());
                e.printStackTrace();
            }
        }

        stat = client.checkExists().forPath(path);
        String value = stat == null ? null : new String(client.getData().forPath(path));
        logger.debug("value:{}", value);
        System.out.println("value:" + value);
    }

    public static void demo() throws Exception {

        String path = "/test_path";
        CuratorFramework client = CuratorFrameworkFactory.builder()
                .connectString("localhost:2181")
                .namespace("/")
                .retryPolicy(new RetryNTimes(Integer.MAX_VALUE, 1000))
                .connectionTimeoutMs(5000).build();
        // 启动 上面的namespace会作为一个最根的节点在使用时自动创建
        client.start();

        // 创建一个节点
        client.create().forPath("/head", new byte[0]);

        // 异步地删除一个节点
        client.delete().inBackground().forPath("/head");

        // 创建一个临时节点
        client.create().withMode(CreateMode.EPHEMERAL_SEQUENTIAL).forPath("/head/child", new byte[0]);

        // 取数据
        client.getData().watched().inBackground().forPath("/test");

        // 检查路径是否存在
        client.checkExists().forPath(path);

        // 异步删除
        client.delete().inBackground().forPath("/head");

        // 注册观察者，当节点变动时触发
        client.getData().usingWatcher(new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                System.out.println("node is changed");
            }
        }).inBackground().forPath("/test");

        // 结束使用
        client.close();
    }
}
